package system.ui;

import system.pojo.Student;
import system.service.StudentService;

import javax.swing.*;
import java.awt.*;
import java.sql.SQLException;

public class UpdateStudentDialog extends JDialog {
    private JTextField nameField, ageField, gradeField;
    private JButton saveButton;
    private StudentService studentService;
    private Student student;

    public UpdateStudentDialog(Frame owner, StudentService studentService, Student student) {
        super(owner, "Update Student", true);
        this.studentService = studentService;
        this.student = student;

        setLayout(new GridLayout(4, 2));
        setSize(300, 200);

        add(new JLabel("Name:"));
        nameField = new JTextField(student.getName());
        add(nameField);

        add(new JLabel("Age:"));
        ageField = new JTextField(String.valueOf(student.getAge()));
        add(ageField);

        add(new JLabel("Grade:"));
        gradeField = new JTextField(student.getGrade());
        add(gradeField);

        saveButton = new JButton("Save");
        saveButton.addActionListener(e -> updateStudent());
        add(saveButton);
    }

    private void updateStudent() {
        try {
            student.setName(nameField.getText());
            student.setAge(Integer.parseInt(ageField.getText()));
            student.setGrade(gradeField.getText());
            studentService.updateStudent(student);
            JOptionPane.showMessageDialog(this, "Student updated successfully");
            dispose();
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Failed to update student: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}
